/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-08-24     yangjie      the first version
 */

/*
 * 程序清单：事件例程
 *
 * 程序会初始化2个线程及初始化一个静态事件对象
 * 一个线程等待于事件对象上，以接收事件；
 * 一个线程发送事件 (事件3/事件5)
*/
#include <aos/aos.h>
#include "aos/cli.h"
#include <debug/dbg.h>

#define THREAD_PRIORITY      9
#define THREAD_STACK_SIZE    2048

#define EVENT_FLAG3 (1 << 3)
#define EVENT_FLAG5 (1 << 5)

/* 事件控制块 */
static aos_event_t event;
/* 线程控制块 */
static aos_task_t tid1 = NULL;
static aos_task_t tid2 = NULL;

/* 线程1入口函数 */
static void thread1_recv_event(void *param)
{
    unsigned int  e;

    /* 第一次接收事件，事件3或事件5任意一个可以触发线程1，接收完后清除事件标志 */
    if(aos_event_get(&event, (EVENT_FLAG3 | EVENT_FLAG5),
                    AOS_EVENT_OR, &e, AOS_WAIT_FOREVER) == 0)
    {
        aos_debug_printf("thread1: OR recv event 0x%x\n", e);
    }

    aos_debug_printf("thread1: delay 1s to prepare the second event\n");
    aos_msleep(1000);

    /* 第二次接收事件，事件3和事件5均发生时才可以触发线程1，接收完后清除事件标志 */
    if(aos_event_get(&event, (EVENT_FLAG3 | EVENT_FLAG5),
                    AOS_EVENT_AND_CLEAR, &e, AOS_WAIT_FOREVER) == 0)
    {
        aos_debug_printf("thread1: AND recv event 0x%x\n", e);
    }
    aos_debug_printf("thread1 leave.\n");
}

/* 线程2入口 */
static void thread2_send_event(void *param)
{
    aos_debug_printf("thread2: send event3\n");
    aos_event_set(&event, EVENT_FLAG3, 0);
    aos_msleep(200);

    aos_debug_printf("thread2: send event5\n");
    aos_event_set(&event, EVENT_FLAG5, 0);
    aos_msleep(200);

    aos_debug_printf("thread2: send event3\n");
    aos_event_set(&event, EVENT_FLAG3, 0);
    aos_debug_printf("thread2 leave.\n");
}

int yoc_event_sample(int argc, char **argv)
{
    int result;

    /* 初始化事件对象 */

    result = aos_event_new(&event,0x0);

    if (result != 0)
    {
        aos_debug_printf("init event failed.\n");
        return -1;
    }
    aos_task_create(&tid1,
                    "thread1",
                    thread1_recv_event, NULL,
                    NULL,
                    THREAD_STACK_SIZE,
                    THREAD_PRIORITY -1,
                    AOS_TASK_AUTORUN);

    aos_task_create(&tid2,
                    "thread2",
                    thread2_send_event, NULL,
                    NULL,
                    THREAD_STACK_SIZE,
                    THREAD_PRIORITY,
                    AOS_TASK_AUTORUN);

    return 0;
}

/* 导出到 msh 命令列表中 */
ALIOS_CLI_CMD_REGISTER(yoc_event_sample, yoc_event_sample,yoc event sample);

